﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Optimization;
using System.Web.Routing;

namespace OptimizationDemo.Optimization
{
    public class Bootstrapper : IHttpModule
    {
        public void Dispose()
        {
        }

        /// <summary>
        /// Init function/Register events
        /// </summary>
        /// <param name="context"></param>
        public void Init(HttpApplication context)
        {
            context.PostMapRequestHandler += (new EventHandler(this.Application_PostMapRequestHandler));
        }

        protected void Application_PostMapRequestHandler(Object source, EventArgs e)
        {
            HttpApplication application = source as HttpApplication;
            HttpContext context = application == null ? null : application.Context;
            if (context != null)
            {
                this.Run(BundleTable.Bundles);
            }
            else
            {
                throw new Exception("Optimization cannot be invoked when context is null");
            }
        }

        /// <summary>
        /// Starts the Custom Bundling Wrapper
        /// </summary>
        /// <param name="bundleCollection"></param>
        private void Run(BundleCollection bundleCollection)
        {
            if (bundleCollection == null)
            {
                throw new Exception("Bundle collection cannot be null");
            }
            new OptimizationDemo.Optimization.CustomOptimizationWrapper().Configure(bundleCollection);
        }
    }
}